package plgcore

import (
	"dgo/MyProj/PrjHttpUtils"
	"dgo/goutils/utils"
	"dgo/plg/plgbase"
	"fmt"
	"gitee.com/ymofen/supervalue"
)

type PlgAppVars struct {
	plgbase.PlgBase
	msglst *utils.SyncCycleList
	lst    *utils.SafeList
}

func (this *PlgAppVars) clean() {
	this.lst.Range(func(val interface{}) bool {
		utils.UnRegisterFactoryVar(val)
		return true
	})
	this.lst.Clear()
}

/*
*

	{
	   "id":"area-vars",
	   "type":"utils.app.vars",
	   "conf":{
	      "vars":{
	         "appid":"xxxz"
	       }
	   }
	}
*/
func (this *PlgAppVars) ReloadConf(conf *wrapper.SuperValue) error {
	if conf == nil {
		return nil
	}

	if this.msglst == nil {
		this.msglst = utils.NewSyncCycleList()
		this.msglst.ConfigMaxSize(1024)
	}

	this.clean()
	vars := conf.ValueByName("vars")
	if vars != nil {
		vars.Range(func(key string, val *wrapper.SuperValue) bool {
			utils.RegisterFactoryVar(key, val.String())
			this.lst.Add(key)
			return true
		})
	}

	return nil
}

func (this *PlgAppVars) OnObjectNotify(sender interface{}, notifytype int, data interface{}) (rval interface{}, err error) {
	if notifytype == utils.NOTIFY_TYPE_SETCONF {
		if conf, ok := data.(*wrapper.SuperValue); ok {
			err = this.ReloadConf(conf)
		} else {
			err = fmt.Errorf("非法的JSON配置")
		}
	} else if notifytype == utils.NOTIFY_TYPE_RELEASE {
		this.ReleaseFlag = 1
		this.clean()
	}
	return
}

func CreatePlgAppVarsFunc(args ...interface{}) (rval interface{}, err error) {
	obj := &PlgAppVars{}
	obj.lst = utils.NewSafeList()
	if len(args) > 0 {
		if str, ok := args[0].(string); ok {
			obj.PlugId = str
		}
	}
	rval = obj
	return
}

func (this *PlgAppVars) OnHttpStatus(rec *PlgHttpRec) (rval interface{}, errcode int, err error) {
	itype := rec.QryAsInt("type", 0)
	if itype == 99 {
		json := wrapper.NewSVObject()
		json.SetKeyValues("now", utils.NowString())
		PrjHttpUtils.JSON2TableRec(rec.RespW, "", json.AsJSONString(false))
	} else if itype == 1 {
		rec.ResponseSyncListNEx(this.msglst)
	} else {
		var sb utils.BytesBuilder
		PrjHttpUtils.AppendIndexBody(&sb, "status", "status?type=99")
		PrjHttpUtils.AppendIndexBody(&sb, "msg-list", "status?type=1&searchval=")
		PrjHttpUtils.ResponseBodyHtml(rec.RespW, sb.String())
	}

	return
}
